package com.realtyreg.webview.servlet;

import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.realtyreg.domain.entity.users.User;
import com.realtyreg.repository.UserRepository;
import com.realtyreg.service.util.ImageUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Petro 10.03.13 18:11
 */
public class ImageServlet extends HttpServlet {
    // дефолтный заголовок
    private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

    private UserRepository userRepository;

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
        userRepository = ctx.getBean(UserRepository.class);
        // инициализируем MIME детектор
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Long id = Long.valueOf(request.getParameter("id"));
        if (id == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ByteArrayOutputStream byteArrayOutputStream = null;
        OutputStream out = null;
        try {
            User user = userRepository.findOne(id);
            if (user == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            String sizeStr = request.getParameter("size");
            Integer size = null;
            if (StringUtils.isNotEmpty(sizeStr)) {
                size = Integer.valueOf(sizeStr);
                if (size != ImageUtil.AVATAR_BIG_SIZE && size != ImageUtil.AVATAR_SMALL_SIZE)
                    size = null;
            }

            byte[] data = ImageUtil.resize(user.getPhoto(), size);
            byteArrayOutputStream = new ByteArrayOutputStream();
            byteArrayOutputStream.write(data);

            try {
                // определение MIME типа изображения
                MimeType mimeTypes = MimeUtil.getMostSpecificMimeType(MimeUtil.getMimeTypes(data));
                response.setContentType(mimeTypes.toString());
                response.setContentLength(data.length);
                response.addHeader("Content-Disposition", "inline; filename="+id+"."+mimeTypes.getSubType());
            } catch (Exception e) {
                response.setContentType(DEFAULT_CONTENT_TYPE);
                response.addHeader("Content-Disposition", "inline; filename=img.jpg");
            }

            out = response.getOutputStream();
            byteArrayOutputStream.writeTo(out);
        }
        catch (Exception e) {
            throw new ServletException(e);
        } finally {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
